package com.servlet.file;

import com.domain.FileClass;
import com.service.FileService;
import com.service.impl.FileServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.UUID;

@WebServlet("/fileAddServlet")
public class FileAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        FileClass file = new FileClass();
        try {
            BeanUtils.populate(file,req.getParameterMap());
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        file.setFile_id(UUID.randomUUID().toString().replaceAll("-","").substring(0,5));
        FileService service = new FileServiceImpl();
        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        if(service.save(file)) {
            resp.getWriter().write("{\"status\":0,\"message\":\"ok\"}");
        }else {
            resp.getWriter().write("{\"status\":1,\"message\":\"err\"}");
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
